package dfs;

import java.util.ArrayList;
import java.util.List;

/**
 * leet-code(39) 组合总和
 *
 * @author Ringo
 * @date 2021/8/18 21:20
 */
public class CombinationSum {

    public static void main(String[] args) {
        int[] candidates = {2, 3, 6, 7};
        System.out.println(newInstance().combinationSum(candidates, 7));
    }

    public static CombinationSum newInstance() {
        return new CombinationSum();
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0)
            return new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        List<List<Integer>> ans = new ArrayList<>();
        dfs(candidates, target, 0, ans, list);
        return ans;
    }

    private void dfs(int[] candidates, int target, int index, List<List<Integer>> ans, List<Integer> list) {
        if (target < 0) return;
        if (target == 0) {
            ans.add(new ArrayList<>(list));
            return;
        }
        for (int i = index; i < candidates.length; ++i) {
            list.add(candidates[i]);
            // 这里又写错了！！
            dfs(candidates, target - candidates[i], i, ans, list);
            list.remove(list.size() - 1);
        }
    }
}
